import { Request, Response, NextFunction } from 'express'
import { createAvatar, findAvatarByUserId } from './avatar.service'
import _ from 'lodash'
import path from 'path'
import fs from 'fs'
import type { AvatarModel } from './avatar.model'

export const store = async (
  req: Request,
  res: Response,
  next: NextFunction
) => {
  const { id: user_id } = req.user
  const fileInfo = _.pick(req.file, ['mimetype', 'filename', 'size'])
  const avatar = {
    ...fileInfo,
    user_id
  }
  try {
    const data = await createAvatar(avatar)
    res.send(data)
  } catch (error) {
    next(error)
  }
}

export const serve = async (
  req: Request,
  res: Response,
  next: NextFunction
) => {
  const { userId } = req.params

  try {
    const avatar = (await findAvatarByUserId(+userId)) as AvatarModel
    if (!avatar) throw new Error('FILE_NOT_FOUND')

    const { size } = req.query as { size: string }
    let filename = avatar.filename
    let root = path.join('uploads', 'avatar')
    let resized = 'resized'

    if (size) {
      const imageSizes = ['large', 'medium', 'small']

      if (!imageSizes.includes(size)) {
        throw new Error('FILE_NOT_FOUND')
      }

      const fileExist = fs.existsSync(
        path.join(
          root,
          resized,
          `${filename}-${size}.${avatar.mimetype.split('/')[1]}`
        )
      )

      if (fileExist) {
        root = root + '/' + resized
        filename = `${filename}-${size}.${avatar.mimetype.split('/')[1]}`
      }
    }

    res.sendFile(filename, {
      root,
      headers: {
        'Content-Type': avatar.mimetype
      }
    })
  } catch (error) {
    next(error)
  }
}
